package com.zlsy.thread.deadlock;

import java.util.Random;

/**
 * @author zhouliang
 * @date 2020/5/13 8:18
 * 多人同时转账依然很危险。
 */
public class MultiTransferMoney {

    private static final int NUM_ACCOUNTS = 500;
    private static final int NUM_MONEY = 1000;
    private static final int NUM_ITERATIONS = 1000000;
    private static final int NUM_THREADS = 20;

    public static void main(String[] args) {
        Random rnd = new Random();
        //定义有多少个账户
        TransferMoney.Account[] accounts = new TransferMoney.Account[NUM_ACCOUNTS];
        for (int i = 0; i < accounts.length; i++) {
            //初始化每个账户
            accounts[i] = new TransferMoney.Account(NUM_MONEY);
        }

        class TransferThread extends Thread {
            @Override
            public void run() {
                //一个子线程完成100W次转账动作
                for (int i = 0; i < NUM_ITERATIONS; i++) {
                    //随机获得一个扣钱账户的下标
                    int from = rnd.nextInt(NUM_ACCOUNTS);
                    //随机获得一个收钱账户的下标
                    int to = rnd.nextInt(NUM_ACCOUNTS);
                    //随机获得一笔转账金额
                    int money = rnd.nextInt(NUM_MONEY);
                    //开始转账
                    TransferMoney.transferMoney(accounts[from], accounts[to], money);
                }
            }
        }

        for (int i = 0; i < NUM_THREADS; i++) {
            new TransferThread().start();
        }
    }


}
